package com.taotao.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.common.utils.CookieUtils;
import com.taotao.web.service.UserService;
import com.taotao.web.thread.UserThreadLocal;
import com.taotao.web.vo.User;

public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	private UserService userService;

	public static final String COOKIE_NAME = "TT_TOKEN";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取cookie信息
		String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
		if (token == null) {
			// 如果token为空,则说明用户没有登录,跳转登录页面
			response.sendRedirect("http://sso.taotao.com/user/login.html");
			return false;
		}
		// 根据token查看用户,

		User user = userService.queryByToken(token);
		if (user == null) {
			// 为空则说明未登录
			response.sendRedirect("http://sso.taotao.com/user/login.html");
			return false;
		}
		UserThreadLocal.set(user);
		// 验证通过,则放行
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
